package org.ling.xuan.dialog;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.Nullable;
import org.ling.xuan.dao.LocalAddDao;
import org.ling.xuan.entity.mo.EmailInitInfo;
import org.ling.xuan.entity.mo.EmailSendInfo;
import org.ling.xuan.entity.mo.EmailSetting;
import org.ling.xuan.pannel.EmailPreviewPanel;
import org.ling.xuan.util.EmailUtil;
import org.ling.xuan.util.LoggerUtil;

import javax.mail.MessagingException;
import javax.swing.*;
import java.io.IOException;
import java.util.List;


public class EmailPreViewDialog extends DialogWrapper {
    private final EmailPreviewPanel panel;
    private final EmailInitInfo emailInitInfo;

    public EmailPreViewDialog(@Nullable Project project, boolean canBeParent, EmailInitInfo emailInitInfo) {
        super(project, canBeParent);
        setTitle("邮件预览");
        panel = new EmailPreviewPanel(emailInitInfo);
        if (emailInitInfo.getEmailSetting().getType().equals("smtp")) {
            setOKButtonText("发送");
        } else {
            setOKButtonText("保存草稿");
        }
        this.emailInitInfo = emailInitInfo;
        setCancelButtonText("放弃发送");
        init();
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return panel;
    }

    public void onOk() throws MessagingException, IOException {
            EmailSendInfo emailSendInfo = panel.getInfo();
            sendEmail(emailInitInfo.getEmailSetting(), emailSendInfo);
            LoggerUtil.log(emailInitInfo.getProject(), "邮件发送成功");
            LocalAddDao.sended(emailInitInfo.getAddInfo().getId());
            Messages.showMessageDialog("邮件发送成功","提示",Messages.getInformationIcon());
    }

    public void sendEmail(EmailSetting es, EmailSendInfo emailSendInfo) throws MessagingException, IOException {
        String host = es.getHost();
        String username = es.getEmail();
        String password = es.getPassword();
        int port = es.getPort();
        boolean ssl = es.isSsl();
        String form = emailSendInfo.getSender();
        String title = emailSendInfo.getTitle();
        String msg = emailSendInfo.getMsg();
        List<String> reviver = emailSendInfo.getReviver();
        List<String> copy = emailSendInfo.getNoticer();
        List<String> files = emailSendInfo.getAttachList();
        EmailUtil.sendEmail(host, username, password, port, ssl, form, title, msg, reviver, copy, files);
    }


}
